package net.gdface.bean.openbeans.factory;

import com.googlecode.openbeans.IntrospectionException;
import com.googlecode.openbeans.PropertyDescriptor;
import java.util.Map;

import net.gdface.annotations.ActiveOnClass;
import net.gdface.bean.openbeans.descriptor.MapPropertyDescriptor;

import static net.gdface.utils.CaseSupport.isCamelcase;
import static net.gdface.utils.CaseSupport.isSnakecase;
import static net.gdface.utils.CaseSupport.toSnakecase;
import static net.gdface.utils.CaseSupport.toCamelcase;

/**
 * @author guyadong
 * @since 2.7.0
 */
@ActiveOnClass(Map.class)
public class MapDescriptorFactory implements PropertyDescriptorFactory {

	@Override
	public PropertyDescriptor descriptorOf(Object bean, String name) throws IntrospectionException {
		if(bean instanceof Map){
			Map<?, ?> map = (Map<?, ?>)bean;
			String key = keyOf(map,name);
			if(null != key) {
				return new MapPropertyDescriptor(null,key);
			}
    		return new MapPropertyDescriptor(null,name);
    	}
		return null;
	}
	/**
	 * 如果Map包含指定的name,则返回name,
	 * 否则尝试转为camelCase或snakeCase查找，如果找到，返回camelCase或snakeCase的键名
	 * @param map
	 * @param name
	 */
	private static String keyOf(Map<?, ?> map,String name) {
		if(null != name) {
			if(map.containsKey(name)) {
				return name;
			}
			if(isCamelcase(name)) {
				name = toSnakecase(name);
				if(map.containsKey(name)) {
					return name;
				}
			}else if(isSnakecase(name)) {
				name = toCamelcase(name);
				if(map.containsKey(name)) {
					return name;
				}
			}
		}
		return null;
	}
}
